package com.woniu.woniu_bx.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.woniu.woniu_bx.exception.TooPoorException;
import com.woniu.woniu_bx.mapper.GoodsMapper;
import com.woniu.woniu_bx.mapper.OrderMapper;
import com.woniu.woniu_bx.mapper.UserMapper;
import com.woniu.woniu_bx.pojo.Goods;
import com.woniu.woniu_bx.pojo.Order;
import com.woniu.woniu_bx.pojo.PageBean;
import com.woniu.woniu_bx.pojo.User;
import com.woniu.woniu_bx.service.OrderService;
import com.woniu.woniu_bx.vo.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName OrderServiceImpl
 * @Description 订单 Service接口实现类
 * @Author 魏才林
 * @Date 2022/8/27 16:32
 * @Version 1.0
 **/

@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public void add(Order order) {
        //初始化下订单的基本信息

        //（1）设置下订单时间
        SimpleDateFormat dateTimeformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        order.setBuyTime(dateTimeformat.format(System.currentTimeMillis()));


        //（2）设置订单编号
        // 根据当日销量，来制作一个订单编号
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
        order.setOrderNum(getOrderNum(dateformat.format(System.currentTimeMillis())));
        System.out.println(order.getOrderNum());

        //（3）设置陪玩操作为'w'：等待处理
        order.setPwOption("w");

        //（4）设置订单初始状态为'1'：待确认（用户下订单后，等待陪玩方处理）
        order.setState("1");
        //（5）增加商品销量
        int goodsId = order.getGoodsId();
        Goods goods = goodsMapper.findCategoryById(goodsId);
        Integer oldSaleNum = goods.getSaleNum();
        int num = order.getNum();
        goods.setId(goodsId);
        goods.setSaleNum(oldSaleNum + num);
        goodsMapper.update(goods);
        //（6）设置订单的金额
        BigDecimal money = goods.getMoney();
        BigDecimal orderMoney = money.multiply(new BigDecimal(num));
        order.setMoney(orderMoney);

        //（7）修改用户（买家）余额
        int userId = order.getUser().getId();
        User user = userMapper.selectById(userId);
        BigDecimal userMoney = user.getMoney();
        int flag = orderMoney.compareTo(userMoney);
        //判断余额是否充足
        if (flag == 1) {
            throw new TooPoorException("账户余额不足，请充值！");
        }
        BigDecimal newUserMoney = userMoney.subtract(orderMoney);
        //（8）修改商户余额
        int sellerId=goods.getUserId();
        User seller = userMapper.findByUserId(sellerId);
        BigDecimal add = seller.getMoney().add(orderMoney);
        seller.setMoney(add);
        userMapper.update(seller);

        user.setMoney(newUserMoney);
        userMapper.update(user);
        orderMapper.insert(order);
    }

    /**
     * 订单删除（逻辑删除）
     *
     * @param orderId
     */
    @Override
    public void delete(Integer orderId) {
        orderMapper.delete(orderId);
    }

    /**
     * 制作订单编号：假设日销量为100000件以内的编号，编号范围（00001~99999）
     *
     * @param curDate
     * @return
     */
    public String getOrderNum(String curDate) {
        // 获得数据库中所有订单的数量
        int orderCount = orderMapper.getNumsOfAllOrderByCurDate(curDate) + 1;
        String orderCountString = "";
        if (0 < orderCount && orderCount < 10) {
            orderCountString = "0000" + orderCount;
        } else if (10 <= orderCount && orderCount < 100) {
            orderCountString = "000" + orderCount;
        } else if (100 <= orderCount && orderCount < 1000) {
            orderCountString = "00" + orderCount;
        } else if (1000 <= orderCount && orderCount < 10000) {
            orderCountString = "0" + orderCount;
        } else {
            orderCountString = "" + orderCount;
        }

        return "bx" + curDate.replace("-", "") + orderCountString;
    }

    /**
     * 获取未确认的订单信息
     *
     * @return
     */
    @Override
    public List<Order> getWaitSureOrder() {
        return orderMapper.getWaitSureOrder();
    }

    /**
     * 获取卖方确认服务完成，买方还未收货的订单
     *
     * @return
     */
    @Override
    public List<Order> getWaitFinishOrder() {
        return orderMapper.getWaitFinishOrder();
    }

    /**
     * 多条件分页查询
     *
     * @param orderVo
     * @param pageSize
     * @return
     */
    @Override
    public PageBean<Order> getByPage(OrderVo orderVo, Integer pageSize) {
        PageBean<Order> pageBean = new PageBean<>();
        Page p = PageHelper.startPage(orderVo.getPage(), pageSize);
        List<Order> data = orderMapper.getByCondition(orderVo.getOrder());
        log.debug("orders:{}" + data);
        pageBean.setData(data);
        pageBean.setCurrPage(orderVo.getPage());
        pageBean.setCurrPageSize(data.size());
        pageBean.setPageSize(pageSize);
        pageBean.setTotalNums((int) p.getTotal());
        pageBean.setTotalPages(p.getPages());
        return pageBean;
    }

    /**
     * 查询所有
     *
     * @return
     */
    @Override
    public List<Order> getAll() {
        return orderMapper.getAll();
    }

    /**
     * 根据商品类别查询订单数量
     *
     * @return
     */
    @Override
    public List<Order> getOrderNumberGroupByCategoryId() {
        return orderMapper.getOrderNumberGroupByCategoryId();
    }

    /**
     * 根据id查询订单
     *
     * @param id
     * @return
     */
    @Override
    public Order getOrderById(int id) {
        return orderMapper.getById(id);
    }

    @Override
    public Order getOrderDetailById(int id) {
        return orderMapper.getOrderDetailById(id);
    }

    @Override
    public List<Order> getByPwUserId(Integer userId) {
        return orderMapper.getByPwUserId(userId);
    }

    /**
     * 根据用户查询订单列表
     * 前台专用
     *
     * @param userId
     * @return
     */
    @Override
    public List<Order> getByUserId(int userId) {
        return orderMapper.getByUserId(userId);
    }

    /**
     * 逻辑删除
     * 前台专用
     *
     * @param id
     */
    @Override
    public void delete(int id) {
        orderMapper.delete(id);
    }

    /**
     * 确认收货
     *
     * @param id
     */
    @Override
    public void confirm(int id) {
        orderMapper.confirm(id);
    }

    /**
     * 服务已完成
     *
     * @param id
     */
    @Override
    public void served(int id) {
        orderMapper.served(id);
    }

    /**
     * 陪玩接受新订单
     *
     * @param id
     */
    @Override
    public void accept(int id) {
        orderMapper.accept(id);
    }

    /**
     * 陪玩拒绝新订单
     *
     * @param id
     */
    @Override
    public void refuse(int id) {
        orderMapper.refuse(id);
    }

    /**
     * @return com.woniu.woniu_bx.pojo.PageBean<com.woniu.woniu_bx.pojo.Order>
     * @Description 根据陪玩id查出其对应订单状态或所有状态的所有订单
     * @Date 12:48 2022/9/2
     * @Author 魏才林
     * @Param [orderVo, pageSize]
     **/
    @Override
    public PageBean<Order> getOrdersByPwIdAndStatus(OrderVo orderVo, Integer pageSize) {

        PageBean<Order> pageBean = new PageBean<>();
        //判断是要查询陪玩的我的服务的，单个状态的订单，还是所有状态的订单
        List<String> status = new ArrayList<>();
        if (orderVo.getStatus() == null || orderVo.getStatus().size() == 0) {
            status.add("1");
            status.add("2");
            status.add("3");
            status.add("4");
            status.add("5");
            status.add("n");
        } else {
            orderVo.getStatus().forEach(s -> status.add(s.toLowerCase()));
        }
        Page p = PageHelper.startPage(orderVo.getPage(), pageSize);
        List<Order> data = orderMapper.getOrdersByPwIdAndStatus(orderVo.getUserId(), status);


        pageBean.setData(data);
        pageBean.setCurrPage(orderVo.getPage());
        pageBean.setCurrPageSize(data.size());
        pageBean.setPageSize(pageSize);
        pageBean.setTotalNums((int) p.getTotal());
        pageBean.setTotalPages(p.getPages());
        return pageBean;
    }

    /**
     * @return com.woniu.woniu_bx.pojo.PageBean<com.woniu.woniu_bx.pojo.Order>
     * @Description 根据普通用户id查出其对应订单状态或所有状态的所有订单
     * @Date 15:17 2022/9/2
     * @Author 魏才林
     * @Param [orderVo, pageSize]
     **/
    @Override
    public PageBean<Order> getOrdersByUserIdAndStatus(OrderVo orderVo, Integer pageSize) {

        PageBean<Order> pageBean = new PageBean<>();
        //判断是要查询陪玩的我的服务的，单个状态的订单，还是所有状态的订单
        List<String> status = new ArrayList<>();
        if (orderVo.getStatus() == null || orderVo.getStatus().size() == 0) {
            status.add("1");
            status.add("2");
            status.add("3");
            status.add("4");
            status.add("5");
            status.add("n");
        } else {
            orderVo.getStatus().forEach(s -> status.add(s.toLowerCase()));
        }
        Page p = PageHelper.startPage(orderVo.getPage(), pageSize);
        List<Order> data = orderMapper.getOrdersByUserIdAndStatus(orderVo.getUserId(), status);


        pageBean.setData(data);
        pageBean.setCurrPage(orderVo.getPage());
        pageBean.setCurrPageSize(data.size());
        pageBean.setPageSize(pageSize);
        pageBean.setTotalNums((int) p.getTotal());
        pageBean.setTotalPages(p.getPages());
        return pageBean;
    }
}
